import { setToken, TokenKey } from '@/services/auth';
import axios from 'axios';
import { request } from 'umi';
import { extend } from 'umi-request';

const ROOT = '/cpasApi';
const settingTimeout = 150 * 1000;
const CPASTableROOT = '/cpasApi';

const requestWithTimeout = extend({
  timeout: settingTimeout, // 设置请求超时时间为10秒（单位是毫秒）
});
const onlineROOT = '/cloudServerApi';
const ROOTTE = '/cpasTeApi';

// 平台地址
export const ROOTS =
  process.env.NODE_ENV === 'development'
    ? '/cpasApi'
    : localStorage.getItem('cpasApiUrl') || window.main?.mainObject?.getWebAppUserConfig()?.cpasApiUrl || '/cpasApi';



async function getCompanyTreeData(code?: any): Promise<API.SerResult> {
  try {
    // api/project/tree/bsdwxydm0001
    const res = await request<API.SerResult>(`${ROOTTE}/companyTreeStructure/getCompanyTree`, {
      // 云转平台
      method: 'GET',
      params: {
        auditCompanyUscc: code,
      }, 
      headers: {
        'Content-Type': 'application/json',
      },
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function companyTreeStructure(data: any): Promise<API.SerResult> {
  try {
    // api/project/tree/bsdwxydm0001
    const res = await request<API.SerResult>(`${ROOTTE}/companyTreeStructure`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}



async function saveTemplate(data?: any): Promise<API.SerResult> {
  try {
    // api/project/tree/bsdwxydm0001
    const res = await request<API.SerResult>(`${ROOTTE}/report/upsert`, {
      // 云转平台
      method: 'POST',
      data, 
      headers: {
        'Content-Type': 'application/json',
      },
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function mergeReport(data?: any): Promise<API.SerResult> {

  try {
    // api/project/tree/bsdwxydm0001
    const res = await request<API.SerResult>(`${ROOTTE}/report/merge`, {
      // 云转平台
      method: 'POST',
      data, 
      headers: {
        'Content-Type': 'application/json',
      },
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function getTemplate(data?: any): Promise<API.SerResult> {
  try {
    // api/project/tree/bsdwxydm0001
    const res = await request<API.SerResult>(`${ROOTTE}/project/${data}`, {
      // 云转平台
      method: 'GET',
      data, 
      headers: {
        'Content-Type': 'application/json',
      },
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}




async function getReport(data?: any): Promise<API.SerResult> {
  try {
    // api/project/tree/bsdwxydm0001
    const res = await request<API.SerResult>(`${ROOTTE}/report/getReport`, {
      // 云转平台
      method: 'POST',
      data, 
      headers: {
        'Content-Type': 'application/json',
      },
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}


/** 登录接口 需要返回 Response */
async function login(body: any, loginHeader: any): Promise<API.SerResult> {
  const r = await request(`${ROOT}/user/login`, {
    // const r = await request(`${ROOT}/auth/login`, {
    timeout: settingTimeout,
    method: 'POST',
    getResponse: true,
    headers: {
      'Content-Type': 'application/json',
      ...loginHeader,
    },
    data: body,
  });
  const { data, response } = r as any;
  if (data.ok) {
    setToken(response.headers.get(TokenKey)!);
  }
  return r.data;
}

/** 退出接口 */
async function logout(): Promise<API.SerResult> {
  return await request<API.SerResult>(`${ROOT}/user/logout`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });
}

/** 获取当前用户信息 接口 */
async function getUserInfo(): Promise<API.SerResult> {
  return await request<API.SerResult>(`${ROOT}/user/getUserInfo`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });
}

/**
 * 获取 sql 模板接口数据
 * @param apiName api名称
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
// http://localhost:8070/cloudServerApi/sqlapis/getApiData
export async function getApiData(
  apiName: string,
  params?: any,
  action?: any,
): Promise<API.SerResult> {
  const pd: API.PostData = {
    name: apiName,
  };
  if (params) {
    pd.params = params;
  }
  // return request<API.SerResult>(`${ROOT}/cpasApi/update`, { // 电子档案
  try {
    //加个名称更加方便查看,后台并不用哈 add by csb 20230716
    const res = await requestWithTimeout<API.SerResult>(
      `${ROOT}/sqlapis/getApiData?api=${apiName}`,
      {
        // 云转平台
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        data: pd,
        action: action ? { ...action } : {},
      },
    );
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function onlineGetApiData(apiName: string, params?: any): Promise<API.SerResult> {
  const pd: API.PostData = {
    name: apiName,
  };
  if (params) {
    pd.params = params;
  }
  // return request<API.SerResult>(`${ROOT}/cpasApi/update`, { // 电子档案
  try {
    const res = await request<API.SerResult>(`${onlineROOT}/sqlapis/getApiData`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// /**
//  * 修改表 支持批量
//  * @param name 表名（包含数据库名）
//  * @param rows 数据
//  * @returns 返回执行成功的行数
//  */
// async function updateTable(name: string, rows: any[]): Promise<API.SerResult> {
//   // return request<API.SerResult>(`${ROOT}/cpasApi/update`, { // 电子档案
//   return request<API.SerResult>(`${ROOT}/sqlapis/update`, {
//     // 云转平台
//     method: 'POST',
//     headers: {
//       'Content-Type': 'application/json',
//     },
//     data: {
//       name,
//       rows,
//     },
//   });
// }

async function getApisData(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`${ROOT}/sqlapis/getApisData`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

/**
 * 获取 nest 接口数据
 * @param apiURL api请求接口地址
 * @param apiMethod api请求方式
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
async function getNestApiData(apiURL: string, apiMethod: string, params?: any): Promise<any> {
  const apiMethodTo = apiMethod.toUpperCase();
  let tempParams = {};

  if (apiMethodTo === 'GET') {
    tempParams = {
      method: apiMethodTo,
      params,
    };
  } else {
    tempParams = {
      method: apiMethodTo,
      data: params,
    };
  }
  try {
    const res = await request<any>(`${ROOT}${apiURL}`, tempParams);
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 查询任意文件夹下有没有存在的文件
async function isHaveTemplateDB(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/template/queryAnyFileIfExistInDisk`, {
      method: 'GET',
      params,
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

export const getCPASTableAipsData = async (paramsName: string, params: any) => {
  try {
    const res: any = await axios.get(`${CPASTableROOT}/cpasTableEngine/${paramsName}`, {
      params,
    });
    return res.data;
  } catch (e) {
    throw e;
  }
};
export const postCPASTableAipsData = async (paramsName: string, params: any) => {
  try {
    const response = await axios.post(`${CPASTableROOT}/cpasTableEngine/${paramsName}`, params);
    return response.data;
  } catch (e) {
    throw e;
  }
};

export const postCPASToolsAipsData = async (paramsName: string, params?: any, action?: any) => {
  try {
    const response = await axios.post(`${CPASTableROOT}/cpasTools/${paramsName}`, params);
    return response.data;
  } catch (e) {
    throw e;
  }
};

const dbname = window.sessionStorage.electronParams
  ? JSON.parse(window.sessionStorage.electronParams).params.DBName
  : 'FI-2017-00001';

/**
 * 保存设计表
 * @param serverData
 */
export const saveTableApi = async (serverData: any) => {
  try {
    const response = await axios.post(`${CPASTableROOT}/cpasTableEngine/saveCpasTable`, {
      dbname,
      ...serverData,
    });
    return response.data;
  } catch (e) {
    throw e;
  }
};

// 文件导出
export async function fileExport(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`${CPASTableROOT}/template/common/copy-files`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

export async function getCurrentZcbfInfo(params: { zcbfID?: string }) {
  try {
    const res = await getApiData('pm.currentZcbfInfo', params);
    if (res.code === 0) {
      return Promise.resolve({
        data: res.data,
        success: true,
      });
    }
    return Promise.resolve({
      data: res.data,
      success: false,
    });
  } catch (error) {
    return Promise.resolve({
      data: 'catch,报错了',
      success: true,
    });
  }
}

export const getDesignTableAipsData = async (paramsName: string, params: any) => {
  try {
    const res: any = await axios.get(`${CPASTableROOT}/cpasTableEngine/${paramsName}`, {
      params,
    });
    return res.data;
  } catch (e) {
    throw e;
  }
};
export async function getApisDataOfApiKey(params?: any): Promise<API.SerResult> {
  try {
    let apiName: string = '';
    let apiNames: string[] = [];
    if (params.apis) {
      for (const key in params.apis) {
        const element = params.apis[key].name;
        if (apiNames.indexOf(element) == -1) {
          apiNames.push(element);
        }
      }
      apiName = apiNames.join(',');
      // const key = Object.keys(params.apis)[0];
      //  apiName = params.apis[key].name;
    }
    const res = await request<API.SerResult>(`${ROOT}/sqlapis/getApisDataOfApiKey?api=${apiName}`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// export
export default getApiData;
export { login, logout, getUserInfo, getApisData, onlineGetApiData, getNestApiData, getCompanyTreeData,saveTemplate,getTemplate,getReport,companyTreeStructure,mergeReport };
